package com.xk.androiddemo;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;

import com.xk.androiddemo.database.AppDatabase;
import com.xk.androiddemo.database.UserBean;
import com.xk.androiddemo.databinding.ActivityRegisterBinding;


public class RegisterActivity extends AppCompatActivity {

ActivityRegisterBinding bind;
private String path;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bind=ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(bind.getRoot());
        onClick();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind=null;
    }


    private static final int PICK_IMAGE_REQUEST = 1;
    private void saveUserInfo() {
        String phone = bind.et1.getText().toString();
        String pwd = bind.et2.getText().toString();
        String name = bind.et3.getText().toString();

        if(name.equals("ad")||name.equals("bm")){
            PopTip.show("特殊用户名不行进行注册");
            return;
        }
        UserBean userBean = new UserBean();
        userBean.setPhone(phone);
        userBean.setPwd(pwd);
        userBean.setName(name);
        if (path != null) {
            userBean.setPath(path);
        }
        WaitDialog.show("正在注册中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserBean search = AppDatabase.getDatabase(RegisterActivity.this).UserDao().getUserByUsername(
                        userBean.getName()
                );
                long s;
                if(search==null){
                   s = AppDatabase.getDatabase(RegisterActivity.this).UserDao().insert(userBean);
                }else {
                    s=-1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s > 0) {
                            WaitDialog.dismiss();
                            PopTip.show("注册成功");
                            finish();
                        } else {
                            WaitDialog.dismiss();
                            TipDialog.show("注册失败", WaitDialog.TYPE.WARNING);
                        }

                    }
                });

            }
        }).start();
    }

     void onClick() {
        bind.button.setOnClickListener(View ->{
                saveUserInfo();
        });
    }

}